#!/bin/bash

# ZooKeeper单节点部署脚本
# 版本：ZooKeeper 3.4.10
# 作者：Your Name
# 日期：2023-10-01

# 配置参数
ZOOKEEPER_VERSION="3.4.10"
ZOOKEEPER_URL="https://archive.apache.org/dist/zookeeper/zookeeper-${ZOOKEEPER_VERSION}/zookeeper-${ZOOKEEPER_VERSION}.tar.gz"
INSTALL_DIR="/opt"
DATA_DIR="/var/lib/zookeeper/data"
LOG_DIR="/var/lib/zookeeper/log"
CLIENT_PORT="2181"

# 检查Java是否安装
if ! command -v java &> /dev/null; then
    echo "Java未安装，正在安装OpenJDK 8..."
    sudo yum install -y java-1.8.0-openjdk-devel
    if [ $? -ne 0 ]; then
        echo "Java安装失败，请手动安装后重试。"
        exit 1
    fi
fi

# 下载ZooKeeper
echo "正在下载ZooKeeper ${ZOOKEEPER_VERSION}..."
wget -q ${ZOOKEEPER_URL} -O /tmp/zookeeper-${ZOOKEEPER_VERSION}.tar.gz
if [ $? -ne 0 ]; then
    echo "下载ZooKeeper失败，请检查网络或URL。"
    exit 1
fi

# 解压ZooKeeper
echo "正在解压ZooKeeper..."
sudo tar -zxvf /tmp/zookeeper-${ZOOKEEPER_VERSION}.tar.gz -C ${INSTALL_DIR} > /dev/null
if [ $? -ne 0 ]; then
    echo "解压ZooKeeper失败，请检查权限或磁盘空间。"
    exit 1
fi

# 创建软链接
sudo ln -sf ${INSTALL_DIR}/zookeeper-${ZOOKEEPER_VERSION} ${INSTALL_DIR}/zookeeper

# 配置环境变量
echo "配置环境变量..."
sudo bash -c "cat > /etc/profile.d/zookeeper.sh" <<EOF
export ZOOKEEPER_HOME=${INSTALL_DIR}/zookeeper
export PATH=\$PATH:\$ZOOKEEPER_HOME/bin
EOF
source /etc/profile.d/zookeeper.sh

# 创建数据目录
echo "创建数据目录..."
sudo mkdir -p ${DATA_DIR} ${LOG_DIR}
sudo chown -R $(whoami):$(whoami) ${DATA_DIR} ${LOG_DIR}

# 配置ZooKeeper
echo "配置ZooKeeper..."
cat > ${INSTALL_DIR}/zookeeper/conf/zoo.cfg <<EOF
tickTime=2000
initLimit=10
syncLimit=5
dataDir=${DATA_DIR}
dataLogDir=${LOG_DIR}
clientPort=${CLIENT_PORT}
maxClientCnxns=60
autopurge.snapRetainCount=3
autopurge.purgeInterval=1
EOF

# 启动ZooKeeper
echo "启动ZooKeeper..."
${INSTALL_DIR}/zookeeper/bin/zkServer.sh start

# 检查状态
echo "检查ZooKeeper状态..."
${INSTALL_DIR}/zookeeper/bin/zkServer.sh status

# 完成
echo "ZooKeeper单节点部署完成！"
echo "客户端连接命令：zkCli.sh -server 127.0.0.1:${CLIENT_PORT}"